
#include<time.h>
#include<unistd.h>
#include<assert.h>
#include"Log.hpp"
#include"TcpServer.hpp"
#include"Socket.hpp"
#include"Protocol.hpp"


//./clientcal ip port

static void Usage(const std::string& proc)
{
    std::cout<<"\nUsage: "<<proc<<"serverip serverport\n"<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);


    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip,serverport);
    if(!r)
    {
        return 1;
    }
    std::string opers = "+-*/%^";
    srand(time(nullptr)^ getpid());
    int cnt = 10;
    std::string inbuffer_stream;
    while(cnt--)
    {
        std::cout<<"第"<<cnt<<"此测试..."<<std::endl;
        int x = rand()%100 + 1;
        usleep(1234);
        int y = rand()%100;
        usleep(4321);
        char oper = opers[rand()%opers.size()];
        Request req(x,y,oper);
        req.DebugPrint();

        std::string package;
        req.Serilize(&package);
        package = Encode(package);
        
        std::cout<<"这是最新的发出去的请求"<<package<<std::endl;
        write(sockfd.Fd(),package.c_str(),sizeof(package));

        char buffer[1024];
        ssize_t n = read(sockfd.Fd(),buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;// "len"\n"result code"\n
            std::cout<<inbuffer_stream<<std::endl;
            std::string content;
            bool r = Decode(inbuffer_stream,&content);
            assert(r);
            
            Response resp;
            r = resp.Deserilize(content);
            assert(r);

            resp.DebugPrint();
        }
        std::cout<<"============================="<<std::endl;
        sleep(1);
    }
    sockfd.Close();

    return 0;
}